package appapi.controller.oider;

import appapi.Request.EquiPageReq;
import appapi.common.ResponseBean;
import appapi.config.CurrentUser;
import appapi.entity.basic.UserInfo;
import appapi.entity.report.*;
import appapi.service.EquipReportService;
import appapi.utils.DateUtil;
import appapi.utils.ExcelUtils;
import appapi.utils.List2MapUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 报表业务功能
 *
 * @author luocheng
 * @version 1.0
 * @date 2023/06/21 11:50
 */
@Api(tags = "报表管理")
@RestController
@RequestMapping(value = "/api/report")
public class ReportController {
    @Resource
    private EquipReportService equipReportService;

    /**
     * 协作队伍机械设备导出
     *
     * @param req
     * @param response
     * @return
     */
    @ApiOperation(value = "导出协作队伍机械设备台帐", notes = "协作队伍机械设备台帐导出接口", produces = "application/octet-stream")
    @GetMapping(value = "/BringEquipRecExport")
    @ApiOperationSupport(ignoreParameters = {"currPage", "pageSize"})
    public ResponseBean BringEquipRecExport(@CurrentUser UserInfo userInfo,EquiPageReq req, HttpServletResponse response) {
        try {
            List<BringEquipEntity> list = equipReportService.getBringEquipList(req, userInfo);
            if (list.size() == 0) {
                return ResponseBean.fail("未查询到数据");
            } else if (list.size() > 5000) {
                return ResponseBean.fail("记录超过5000，请重新选择查询条件");
            } else {
                ExcelUtils.exportExcel(list, "协作队伍机械设备台账记录", "协作队伍机械设备台账记录sheet", BringEquipEntity.class, "协作队伍机械设备台账记录", response);
                return ResponseBean.success();
            }
        } catch (Exception e) {
            return ResponseBean.fail("协作队伍机械设备台账记录导出异常");
        }
    }

    @ApiOperation(value = "协作队伍机械设备台帐--打印")
    @GetMapping(value = "/getBringListByPrint")
    public ResponseBean getBringListByPrint(@CurrentUser UserInfo userInfo,EquiPageReq req) {
        List<BringEquipEntity> list = equipReportService.getBringEquipList(req,userInfo);
        if (list.size() == 0) {
            return ResponseBean.fail("数据源为空");
        } else if (list.size() > 5000) {
            return ResponseBean.fail("打印数量超过5000条，请重新查询打印！");
        }
        StringBuilder sb = new StringBuilder();
        //表头
        sb.append("<table border='0' cellspacing='0' cellpadding='1' width='100%' style='border-collapse: collapse;font-size: 24px; line-height: 22px;' bordercolor='#333333'>");
        sb.append("<tr  border='0' height='50px'><th colspan='13' style='font-size: 24px;'>协作队伍机械设备台帐</th></tr>");
        sb.append("   <tr height='30' style='font-size: 16px;'><td align='left' style='padding-right:5%;'colspan='4'>项目名称</td></tr>");
        sb.append("</table>");
        //内容
        sb.append("<table border='1' cellspacing='0' cellpadding='1' width='100%' style='border-collapse: collapse;font-size: 12px; line-height: 22px;' bordercolor='#333333'>");
        sb.append("<tr align='center'\">" +
                "<td rowspan='2'><b>序号</b></td>" +
                "<td rowspan='2'><b>设备名称</b></td>" +
                "<td rowspan='2'><b>管理编号</b></td>" +
                "<td rowspan='2'><b>规格型号</b></td>" +
                "<td rowspan='2'><b>功率(kw)</b></td>" +
                "<td rowspan='2'><b>生产厂家</b></td>" +
                "<td rowspan='2'><b>出厂日期</b></td>" +
                "<td rowspan='2'><b>与合同是否相符</b></td>" +
                "<td rowspan='2'><b>作业人员姓名</b></td>" +
                "<td rowspan='2'><b>作业证名称</b></td>" +
                "<td rowspan='2'><b>作业证编号</b></td>" +
                "<td rowspan='2'><b>发证机关</b></td>" +
                "<td rowspan='2'><b>使用地点</b></td>" +
                "<td rowspan='2'><b>协作队伍名称</b></td>" +
                "<td rowspan='2'><b>自有或租赁</b></td>" +
                "<td rowspan='2'><b>出租单位名称</b></td>" +
                "<td rowspan='2'><b>合同编号</b></td>" +
                "<td colspan='3'><b>时间</b></td>" +
                "<td rowspan='2'><b>备注</b></td>" +
                "</tr>" +
                "<tr align='center' >" +
                "<td><b>起止日期</b></td>" +
                "<td><b>合同中止日期</b></td>" +
                "<td><b>实际中止日期</b></td>" +
                "</tr></thead>");
        sb.append("<tbody>");
        for (BringEquipEntity m : list) {
            sb.append("<tr >" +
                    "<td valign='middle' align='center'>" + m.getSno() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getEquipName() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getManaNumber() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getEquipModel() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getEquipPower() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getEquipProduct() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getEquipProductDate() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getContMatch() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getOperName() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getOperItemName() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getCertificateCode() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getCertificateIssueunit() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getEquipAddress() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getCollTeam() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getEquipCategory() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getRentalUnit() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getContNumber() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getContQuitDate() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getActQuitDate() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getEquipStartUse() + "</td>" +
                    "<td valign='middle' align='center'>" + m.getEquipNote() + "</td>");
            sb.append("</tr>");
        }
        sb.append("</tbody></table>");
        return ResponseBean.success(list.size(), sb.toString());

    }

    @ApiOperation(value = "导出租赁设备台账--打印", notes = "导出租赁设备台账--打印", produces = "application/octet-stream")
    @GetMapping(value = "/LeasedEquipRecByPrint")
    @ApiOperationSupport(ignoreParameters = {"currPage", "pageSize"})
    public ResponseBean LeasedEquipRecByPrint(@CurrentUser UserInfo userInfo, EquiPageReq req) {
        try {

            if (ObjectUtils.isEmpty(req.getOrgaName())) {
                return ResponseBean.fail("组织机构名称不能为空!");
            }
            LeasedEquipEntity entity = new LeasedEquipEntity();
            List<LeasedEquipEntity> datas = equipReportService.getLeasedEquipList(req, userInfo);


            List<Map<String, Object>> list = List2MapUtil.objectList2ListMap(datas);

            List<KeyValueEntity> titles = getTitle(PoiPublicUtil.getClassFields(entity.getClass()));

            if (datas.size() == 0) {
                return ResponseBean.fail("未查询到数据");
            } else if (datas.size() > 5000) {
                return ResponseBean.fail("记录超过5000，请重新选择查询条件");
            }
//            //取出标头
            //Set<String> titles = list.stream().map(Map::keySet).collect(Collectors.toList()).get(0);
            StringBuilder sb = new StringBuilder();
            //表头
            sb.append("<table border='0' cellspacing='0' cellpadding='1' width='100%' style='border-collapse: collapse;font-size: 24px; line-height: 22px;' bordercolor='#333333'>");
            sb.append("<tr border='0' height='50px'><th colspan='13' style='font-size: 24px;'>租 赁 设 备 台 账</th></tr>");
            sb.append("<tr height='30' style='font-size: 16px;'><td align='left' style='padding-right:5%;' colspan='4'>组织机构名称:  ");
            sb.append(req.getOrgaName());
            sb.append("</td></tr>");
            sb.append("<tr height='30' style='font-size: 16px;'><td align='left' style='padding-right:5%;'colspan='4'>填报日期:  ");
            sb.append(DateUtil.getDate2String(new Date()));
            sb.append("</td></tr>");
            sb.append("</table>");
            //内容
            sb.append("<table border='1' cellspacing='0' cellpadding='1' width='100%' style='border-collapse: collapse;font-size: 12px; line-height: 22px;' bordercolor='#333333'>");
            sb.append("<thead><tr  align='center'  bgcolor=#cccccc>");
            titles.forEach(title -> {
                //标头
                sb.append("<td><b>");
                sb.append(title.getTitle());
                sb.append("</b></td>");
            });
            sb.append("</tr></thead>");
            sb.append("<tbody>");

            list.forEach(data -> {
                sb.append("<tr >");
                titles.forEach(title -> {
                    sb.append("<td valign='middle' align='center'>");
                    sb.append(data.get(title.getValue()) == null ? "" : data.get(title.getValue()));
                    sb.append("</td>");
                });
                sb.append("</tr>");
            });

            sb.append("</tbody></table>");
            return ResponseBean.success(list.size(), sb.toString());
        } catch (Exception e) {
            return ResponseBean.fail("队伍自带设备台账记录打印异常".concat(e.getMessage()));
        }
    }

    private static List<KeyValueEntity> getTitle(Field[] entity) {
        Field[] fileds = entity;
        //拿到表的标头和对应字段
        List<KeyValueEntity> titles = Arrays.stream(fileds).map(field -> {
            KeyValueEntity col = new KeyValueEntity();
            Excel excel = field.getAnnotation(Excel.class);
            col.setTitle(excel.name());
            col.setValue(field.getName());
            return col;
        }).collect(Collectors.toList());
        return titles;
    }

    @ApiOperation(value = "导出租赁设备台账", notes = "导出租赁设备台账", produces = "application/octet-stream")
    @GetMapping(value = "/LeasedEquipRecExport")
    @ApiOperationSupport(ignoreParameters = {"currPage", "pageSize"})
    public ResponseBean LeasedEquipRecExport(@CurrentUser UserInfo userInfo, EquiPageReq req, HttpServletResponse response) {
        try {
            List<LeasedEquipEntity> list = equipReportService.getLeasedEquipList(req,userInfo);
            if (list.size() == 0) {
                return ResponseBean.fail("未查询到数据");
            } else if (list.size() > 5000) {
                return ResponseBean.fail("记录超过5000，请重新选择查询条件");
            } else {
                ExcelUtils.exportExcel(list, "租赁设备台账", "租赁设备台账sheet", LeasedEquipEntity.class, "租赁设备台账", response);
                return ResponseBean.success();
            }
        } catch (Exception e) {
            return ResponseBean.fail("队伍租赁设备台账记录导出异常: ".concat(e.getMessage()));
        }
    }


    @ApiOperation(value = "导出自有机械设备台账", notes = "导出自有机械设备台账", produces = "application/octet-stream")
    @GetMapping(value = "/SelfEquipRecExport")
    @ApiOperationSupport(ignoreParameters = {"currPage", "pageSize"})
    public ResponseBean SelfEquipRecExport(@CurrentUser UserInfo userInfo, EquiPageReq req, HttpServletResponse response) {
        try {
            List<SelfEquipEntity> list = equipReportService.getSelfEquipList(req,userInfo);
            if (list.size() == 0) {
                return ResponseBean.fail("未查询到数据");
            } else if (list.size() > 5000) {
                return ResponseBean.fail("记录超过5000，请重新选择查询条件");
            } else {
                ExcelUtils.exportExcel(list, "自有机械设备台账", "自有机械设备台账sheet", SelfEquipEntity.class, "自有机械设备台账", response);
                return ResponseBean.success();
            }
        } catch (Exception e) {
            return ResponseBean.fail("自有机械设备台账记录导出异常");
        }
    }

    @ApiOperation(value = "自有机械设备台账--打印", notes = "自有机械设备台账记录导出接口", produces = "application/octet-stream")
    @ApiOperationSupport(ignoreParameters = {"currPage", "pageSize"})
    @GetMapping("/SelfEquipListByPrint")
    public ResponseBean SelfEquipListByPrint(@CurrentUser UserInfo userInfo,@Validated EquiPageReq req) {
        try {
            if (ObjectUtils.isEmpty(req.getOrgaName())) {
                return ResponseBean.fail("组织机构名称不能为空!");
            }
            SelfEquipEntity selfEquipEntity = new SelfEquipEntity();

            List<SelfEquipEntity> datas = equipReportService.getSelfEquipList(req, userInfo);
            List<Map<String, Object>> list = List2MapUtil.objectList2ListMap(datas);

            List<KeyValueEntity> titles = getTitle(PoiPublicUtil.getClassFields(selfEquipEntity.getClass()));

            if (datas.size() == 0) {
                return ResponseBean.fail("未查询到数据");
            } else if (datas.size() > 5000) {
                return ResponseBean.fail("记录超过5000，请重新选择查询条件");
            }
            //取出标头
//            Set<String> titles = list.stream().map(Map::keySet).collect(Collectors.toList()).get(0);
            StringBuilder sb = new StringBuilder();
            //表头
            sb.append("<table border='0' cellspacing='0' cellpadding='1' width='100%' style='border-collapse: collapse;font-size: 24px; line-height: 22px;' bordercolor='#333333'>");
            sb.append("<tr border='0' height='50px'><th colspan='13' style='font-size: 24px;'>中交一公局集团有限公司</th></tr>");
            sb.append("<tr border='0' height='50px'><th colspan='13' style='font-size: 24px;'>自 有 机 械 设 备 台 帐(季报)</th></tr>");
            sb.append("<tr height='30' style='font-size: 16px'>" +
                    "<td align='center'  colspan='4'>" +
                    "______年_____季度" +
                    "</td>" +
                    "</tr>");
            sb.append("<div style='display: flex; justify-content: space-between;'>");
            sb.append("<tr height='30' style='font-size: 16px;'><td align='left' colspan='4'>组织机构名称:  ");
            sb.append(req.getOrgaName());
            sb.append("</td></tr>");
            sb.append("<tr height='30' style='font-size: 16px;'><td align='left' colspan='4'>填报日期:  ");
            sb.append(DateUtil.getDate2String(new Date()));
            sb.append("</td></tr>");
            sb.append("</div>");
            sb.append("</table>");
            //内容
            sb.append("<table border='1' cellspacing='0' cellpadding='1' width='100%' style='border-collapse: collapse;font-size: 12px; line-height: 22px;' bordercolor='#333333'>");
            sb.append("<thead><tr  align='center'  bgcolor=#cccccc>");
            titles.forEach(title -> {
                //标头
                sb.append("<td><b>");
                sb.append(title.getTitle());
                sb.append("</b></td>");
            });
            sb.append("</tr></thead>");
            sb.append("<tbody>");
            list.forEach(data -> {
                sb.append("<tr >");

                titles.forEach(title -> {
                    sb.append("<td valign='middle' align='center'>");
                    sb.append(data.get(title.getValue()) == null ? "" : data.get(title.getValue()));
                    sb.append("</td>");
                });

                sb.append("</tr>");
            });

            sb.append("</tbody></table>");
            sb.append("<div style='display: flex; justify-content: space-between;'>");
            sb.append("<tr height='30' style='font-size: 16px'>" +
                    "<td align='left'  colspan='4'>" +
                    "主管部门负责人: " +
                    "</td>" +
                    "</tr>");
            sb.append("<tr height='30' style='font-size: 16px'>" +
                    "<td align='center'  colspan='4'>" +
                    "部门负责人: " +
                    "</td>" +
                    "</tr>");
            sb.append("<tr height='30' style='font-size: 16px;margin-right: 100px;'>" +
                    "<td align='right'  colspan='4'>" +
                    "制表: " +
                    "</td>" +
                    "</tr>");
            sb.append("</div>");
            return ResponseBean.success(list.size(), sb.toString());
        } catch (Exception e) {
            return ResponseBean.fail("自有机械设备台账记录导出打印异常".concat(e.getMessage()));
        }
    }

    /**
     * 特种设备台账记录导出
     *
     * @param equiPageReq
     * @param response
     * @return
     */
    @ApiOperation(value = "特种设备台账记录导出", notes = "特种设备台账记录导出接口", produces = "application/octet-stream")
    @GetMapping(value = "/SpecialEquipRecExport")
    @ApiOperationSupport(ignoreParameters = {"currPage", "pageSize"})
    public ResponseBean SpecialEquipRecExport(EquiPageReq equiPageReq, HttpServletResponse response) {
        try {
            List<SpecialEquipEntity> list = equipReportService.getSpecialEquipList(equiPageReq);
            if (list.size() == 0) {
                return ResponseBean.fail("未查询到数据");
            } else if (list.size() > 5000) {
                return ResponseBean.fail("记录超过5000，请重新选择查询条件");
            } else {
                ExcelUtils.exportExcel(list, "特种设备台账记录", "特种设备台账记录sheet", SpecialEquipEntity.class, "特种设备台账记录", response);
                return ResponseBean.success();
            }
        } catch (Exception e) {
            return ResponseBean.fail("特种设备台账记录导出异常");
        }
    }

    @ApiOperation(value = "特总设备台账--打印")
    @GetMapping("/getRechargeListByPrint")
    public ResponseBean SpecialEquipListByPrint(@Validated EquiPageReq req) {
        //查询数据
        List<SpecialEquipEntity> list = equipReportService.getSpecialEquipList(req);
        if (list.size() == 0) {
            return ResponseBean.fail("数据源为空");
        } else if (list.size() > 5000) {
            return ResponseBean.fail("打印数量超过5000条，请重新查询打印！");
        }
        StringBuilder sb = new StringBuilder();
        //表头
        sb.append("<table border='0' cellspacing='0' cellpadding='1' width='100%' style='border-collapse: collapse;font-size: 24px; line-height: 22px;' bordercolor='#333333'>");
        sb.append("<tr  border='0' height='50px'><th colspan='13' style='font-size: 24px;'>特种设备及操作员台账</th></tr>");
        sb.append("   <tr height='30' style='font-size: 16px;'><td align='left' style='padding-right:5%;'colspan='4'>项目名称</td></tr>");
        sb.append("</table>");
        //内容
        sb.append("<table border='1' cellspacing='0' cellpadding='1' width='100%' style='border-collapse: collapse;font-size: 12px; line-height: 22px;' bordercolor='#333333'>");
        sb.append("<tr  align='center'  bgcolor=\"#cccccc\"><td><b>设备名称</b></td>" +
                "<td><b>管辖地号</b></td><td><b>规格型号</b></td><td><b>出厂日期</b></td><td><b>与合同是否项</b></td><td><b>生产厂家</b></td>" +
                "<td><b>安拆许可证编号</b></td><td><b>安检报告编号</b></td><td><b>下次复审日期</b></td><td><b>使用登记证编号</b></td><td><b>操作手姓名</b></td>" +
                "<td><b>作业代码编号</b></td><td><b>操作证编号</b></td><td><b>操作证发证机关</b></td><td><b>下次复审日期</b></td><td><b>协作队伍名称</b>" +
                "</td><td><b>进场日期</b></td><td><b>退场日期</b></td><td><b>作业地点</b></td><td><b>状态</b></td><td><b>状态</b></td></tr></thead>");
        sb.append("<tbody>");
        for (SpecialEquipEntity m : list) {
            sb.append("<tr ><td valign='middle' align='center'>" + m.getEquipName() + "</td>");

//            if(m.getEquidTerminal()==null) {
//                sb.append("<td valign='middle' align='center'></td>");
//            }else {
//                sb.append("<td valign='middle' align='center'>" + m.getEquidTerminal() + "</td>");
//            }
            sb.append("</tr>");
        }
        sb.append("</tbody></table>");
        return ResponseBean.success(list.size(), sb.toString());
    }

}

